#pragma once
#include <iostream>
#include <string>
#include <sys/epoll.h>
#include <unistd.h>
#include <cstring>
#include "../../logs/log.h"

namespace EpollerModule
{
    const static int default_epfd = -1;
    const static int size = 128;
    class Epoller
    {
    public:
        Epoller() {}
        void InitEpoll()
        {
            _epfd = ::epoll_create(size);
            if (_epfd == default_epfd)
            {
                FATAL("epoll_create error!, %s: %d", strerror(errno), errno);
                exit(4);
            }
            INFO("epoll_create success!, epfd: %d", _epfd);
        }

        void AddEvent(int fd, uint32_t events)
        {
            struct epoll_event ev;
            ev.data.fd = fd;
            ev.events = events;

            int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, fd, &ev);
            if (n < 0)
            {
                ERROR("epoll_ctl add errro, %s : %d\n", strerror(errno), errno);
            }
        }

        void DelEvent(int sockfd)
        {
            int n = ::epoll_ctl(_epfd, EPOLL_CTL_DEL, sockfd, nullptr);
            if (n < 0)
            {
               ERROR("epoll_ctl del error, %s : %d\n", strerror(errno), errno);
            }
        }
        int Wait(struct epoll_event *revs, int maxevents, int timeout)
        {
            int n = ::epoll_wait(_epfd, revs, maxevents, timeout);
            return n;
        }

        ~Epoller()
        {
            if (_epfd >= 0)
            {
                close(_epfd);
            }
            INFO("epoll close success!");
        }

    private:
        int _epfd;
    };
}
